/**
 * 测试工具函数
 * 
 * 功能特性：
 * - API mock工具
 * - 组件测试工具
 * - 数据生成工具
 */

import { render, RenderOptions } from '@testing-library/react';
import { ReactElement } from 'react';
import { BrowserRouter } from 'react-router-dom';

// 自定义渲染器，包含路由提供者
const customRender = (
  ui: ReactElement,
  options?: Omit<RenderOptions, 'wrapper'>
) => render(ui, { wrapper: BrowserRouter, ...options });

// 重新导出所有testing-library工具
export * from '@testing-library/react';
export { customRender as render };

// API响应mock工具
export const createMockApiResponse = <T,>(data: T, status = 200) => {
  return Promise.resolve({
    ok: status >= 200 && status < 300,
    status,
    json: () => Promise.resolve(data),
    data,
  } as any);
};

// 创建测试数据生成器
export const testDataGenerator = {
  // 生成智能体测试数据
  createAgent: (overrides = {}) => ({
    id: 'test-agent-id',
    name: 'Test Agent',
    description: 'Test agent description',
    status: 'Running',
    systemPrompt: 'You are a helpful assistant',
    modelConfigId: 'test-model-config-id',
    isActive: true,
    createdAt: '2024-01-15T00:00:00Z',
    updatedAt: '2024-01-15T00:00:00Z',
    modelConfig: {
      id: 'test-model-config-id',
      name: 'Test Model Config',
      provider: 'OpenAI',
      model: 'gpt-4',
    },
    ...overrides,
  }),

  // 生成模型配置测试数据
  createModelConfig: (overrides = {}) => ({
    id: 'test-model-config-id',
    name: 'Test Model Config',
    provider: 'OpenAI',
    model: 'gpt-4',
    maxTokens: 4000,
    temperature: 0.7,
    isActive: true,
    createdAt: '2024-01-15T00:00:00Z',
    ...overrides,
  }),

  // 生成分页响应数据
  createPagedResponse: <T,>(items: T[], totalCount = items.length) => ({
    items,
    totalCount,
  }),

  // 创建API错误响应
  createApiError: (message: string, status = 400) => {
    const error = new Error(message) as any;
    error.response = {
      status,
      data: { message },
    };
    return error;
  },
};

// Mock axios
export const mockAxios = {
  get: jest.fn(),
  post: jest.fn(),
  put: jest.fn(),
  delete: jest.fn(),
  create: jest.fn(() => mockAxios),
  interceptors: {
    request: {
      use: jest.fn(),
    },
    response: {
      use: jest.fn(),
    },
  },
};

// 模拟localStorage
export const mockLocalStorage = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
};